<template>
  <div class="upload-section">
    <a-upload-dragger
      v-model:fileList="fileList"
      action="https://upload-z2.qiniup.com"
      :data="dataParam"
      :capture="null"
      name="file"
      :multiple="true"
      :max-count="10"
      :before-upload="beforeUpload"
      @change="handleChange"
      @drop="handleDrop">
      <p class="drag-icon"><c-icon icon="CloudUploadOutlined" /></p>
      <p class="upload-txt">点击上传或拖拽文件到区域</p>
      <p class="upload-txt-info">支持单次或批量上传。单次最多支持10张图片同时上传</p>
    </a-upload-dragger>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { getFingerPrint } from '@wattjs/network'
import { ll } from '../utils'
import { getUploadToken } from '../api/upload'

let clientId = ll.get('CLIENT-ID')
let tempList
const fileList = ref([])

const handleDrop = e => {
  console.log(e)
}

const handleChange = info => {
  const status = info.file.status
  if (status === 'done') {

  }
}

const dataParam = (file) => {
  const { key, token, clientId, uuid, businessType } = tempList.find(ret => ret.name === file.name)
  return { key, token, 'x:deviceId': clientId, 'x:uid': uuid, 'x:type': businessType }
}

const beforeUpload = async (file, filse) => {
  if (!clientId) {
    clientId = await getFingerPrint()
    ll.set('CLIENT-ID', clientId)
  }
  tempList = filse
  const { key, token, url, uid, type } = await getUploadToken.send({
    businessType: 9, // cdn
    fileKey: (ll.get('op_id') ? `${ll.get('op_id')}/` : '') + file.name
  }).catch(() => ({}))
  if (!token) return Promise.reject(new Error('token is empty'))
  const index = filse.findIndex(ret => ret.name === file.name)
  filse[index].key = key
  filse[index].token = token
  filse[index].clientId = clientId
  filse[index].uuid = uid
  filse[index].businessType = type
  return Promise.resolve(file)
}
</script>
<style lang="less">
.upload-section {
  margin-top: 15px;

  .drag-icon {
    font-size: 36px;
    color: #1890ff;
  }
  .upload-txt {
    font-size: 15px;
    color: #333;
    line-height: 28px;
    font-weight: 600;
  }
  .upload-txt-info {
    font-size: 12px;
    color: #999;
  }
}
</style>
